package com.biShe.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.biShe.entity.RoleCSysMenu;
import com.biShe.entity.SysMenu;
import com.biShe.entity.User;
import com.biShe.entity.UserCRole;
import com.biShe.mapper.RoleCSysMenuMapper;
import com.biShe.mapper.SysMenuMapper;
import com.biShe.mapper.UserCRoleMapper;
import com.biShe.mapper.UserMapper;
import com.biShe.utils.Result;
import com.biShe.vo.MenuVO;
import com.biShe.vo.MyOrderVO;
import com.biShe.vo.OrdersVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小刘
 * @since 2023-04-10
 */
@Configuration
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCRoleMapper userCRoleMapper;

    @Autowired
    private  RoleCSysMenuMapper roleCSysMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;



    @ApiOperation(value="根据用户名，密码获取登录信息", notes="返回指定的用户角色号")
//    @ApiImplicitParam(name = "user",value = "用户信息", required = true, dataType = "User")
    @GetMapping("/login/{username}/{password}")
    public Result Login(@PathVariable("username") String username, @PathVariable("password") String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);

        User user1 = new User();
        user1 = userMapper.selectOne(queryWrapper);
        QueryWrapper<UserCRole> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id",user1.getId());
        UserCRole userCRole= userCRoleMapper.selectOne(queryWrapper1);

        Integer rid = userCRole.getRid();
        return Result.succ(rid);
    }

    @ApiOperation(value="根据用户名，密码获取登录信息", notes="返回指定的用户信息")
//    @ApiImplicitParam(name = "user",value = "用户信息", required = true, dataType = "User")
    @GetMapping("/loginInfo/{username}/{password}")
    public Result Login2(@PathVariable("username") String username, @PathVariable("password") String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);

        User user1 = new User();
        user1 = userMapper.selectOne(queryWrapper);

        return Result.succ(user1);
    }


    /**
     * 查找所有用户
     *
     * @return 返回所有用户信息列表
     */
    @ApiOperation(value="获取所有用户信息", notes="返回所有用户信息列表")
    @GetMapping("/list/{page}/{size}")
    public Result list(@PathVariable("page") String page,@PathVariable("size") String size) {
        Page pageHelper = PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(size));
        List<User> userList = userMapper.selectList(null);
        PageInfo pageInfo = new PageInfo(userList);
        return Result.succ(pageInfo);
    }

    /**
     * 查找所有用户
     *
     * @return 返回所有用户信息列表
     */
    @ApiOperation(value="获取所有用户信息", notes="返回所有用户信息列表")
    @GetMapping("/list")
    public Result list() throws Exception {
        List<User> userList = userMapper.selectList(null);
        PageInfo pageInfo = new PageInfo(userList);

        return Result.succ(pageInfo);

    }


    /**
     * 根据ID查找用户
     *
     * @param id 用户ID
     * @return 返回指定ID的用户信息
     */
    @ApiOperation(value="根据ID获取用户信息", notes="返回指定ID的用户信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Int", paramType = "path")
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.fail("该用户不存在");
        }
        return Result.succ(user);
    }

    /**
     * 添加新用户
     *
     * @param user 新用户信息
     * @return 返回添加结果
     */
    @ApiOperation(value="添加新用户", notes="添加新用户信息")
    @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
    @PostMapping("/")
    public Result add(@RequestBody User user) {
        int rows = userMapper.insert(user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",user.getMobile());
        queryWrapper.eq("password",user.getPassword());
        User user1 = userMapper.selectOne(queryWrapper);
        if (rows == 0) {
            return Result.fail("添加新用户失败");
        }
        return Result.succ(user1);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @return 返回更新结果
     */
    @ApiOperation(value="修改用户信息", notes="修改指定用户的信息")
    @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
    @PutMapping("/")
    public Result update(@RequestBody User user) {
        int rows = userMapper.updateById(user);
        if (rows == 0) {
            return Result.fail("更新用户信息失败");
        }
        return Result.succ("更新用户信息成功");
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 返回删除结果
     */
    @ApiOperation(value="删除用户信息", notes="删除指定ID的用户信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Int", paramType = "path")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        int rows = userMapper.deleteById(id);
        if (rows == 0) {
            return Result.fail("删除用户信息失败");
        }
        return Result.succ("删除用户信息成功");
    }


    /**
     * 根据手机号模糊查询用户信息
     *
     * @param mobile 手机号
     * @return 返回符合条件的用户信息列表
     */
    @ApiOperation(value="根据手机号模糊查询用户信息", notes="返回符合条件的用户信息列表")
    @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String", paramType = "path")
    @GetMapping("/search/{mobile}")
    public Result search(@PathVariable("mobile") String mobile) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("mobile", mobile);
        List<User> userList = userMapper.selectList(wrapper);
        if (userList.isEmpty()) {
            return Result.fail("暂无匹配结果");
        }
        return Result.succ(userList);
    }

//    /**
//     * 根据用户名，密码查询用户登录信息,查询出需要的菜单
//     *
//     * @param mobile 手机号
//     * @return 返回符合条件的用户信息列表
//     */
//    @ApiOperation(value="根据手机号模糊查询用户信息", notes="返回符合条件的用户信息列表")
//    @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String", paramType = "path")
//    @PostMapping("/login")
//    public Result login(@RequestBody User user) {
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
////        wrapper.eq("mobile")
////        wrapper.like("mobile", mobile);
//        List<User> userList = userMapper.selectList(wrapper);
//        if (userList.isEmpty()) {
//            return Result.fail("暂无匹配结果");
//        }
//        return Result.succ(userList);
//    }




    /**
     * 根据用户名，密码查询用户登录信息,查询出需要的菜单
     *
     * @param
     * @return
     */
    @ApiOperation(value="根据用户名查询菜单", notes="返回符合条件的餐单")
    @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "path")
    @GetMapping("/getMenu/{username}")
    public Result getMenuByCurrentUser(@PathVariable("username") String username) {
        List<MenuVO>  menus = new ArrayList<>();
            //获取当前登录用户的用户名 username

            //根据用户name字段获取当前用户的角色,去user_c_role里，根据username查出rid，一个username可能查出多个角色的role_id

            QueryWrapper<UserCRole> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("username",username);
            List<UserCRole> userCRoles = userCRoleMapper.selectList(queryWrapper1);
            //使用userCRoles里的角色rid ，去role_c_sys_menu查一级菜单的mid，菜单类型（M目录 C菜单 F按钮），用mid把一级菜单的信息存成列表
            for (UserCRole item : userCRoles) {
                //role_c_sys_menu
                QueryWrapper<RoleCSysMenu> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("rid",item.getRid());
                List<RoleCSysMenu> roleMenus = roleCSysMenuMapper.selectList(queryWrapper2);
                //获得mid，在roleMenus里，用mid去获取最外层的一级菜单
                for (RoleCSysMenu menu : roleMenus) {
                    MenuVO myMenu = new MenuVO();
                    //用mid去获取最外层的一级菜单，把菜单需要的部分拷贝到VO
                    SysMenu sysMenu = sysMenuMapper.selectById(menu.getMid());
                    BeanUtils.copyProperties(sysMenu,myMenu);
                    if (!menus.contains(myMenu)) {
                        menus.add(myMenu);
                    }
                }
            }
            //添加二级菜单
            List<MenuVO> result = handleMenus(menus);
            //添加三级菜单
//            List<MenuVO> fin_result = handleChildMenus(result);
            return Result.succ(result);
        }

        /**
         * 根据一级菜单获取二级菜单
         *
         * @param menus 一级菜单
         * @return 添加了二级菜单的一级菜单
         */

        public List<MenuVO> handleMenus(List<MenuVO> menus) {
            List<MenuVO> children = new ArrayList<>();
            for (MenuVO item : menus) {
                //获取父节点的id为一级菜单id的二级菜单，转化为Vo类型，然后加入到一级菜单的孩子节点中
               QueryWrapper<SysMenu> queryWrapper3 = new QueryWrapper<>();
               queryWrapper3.eq("parentid",item.getId());
               List<MenuVO> menuVOS = new ArrayList<>();
               List<SysMenu> sysMenus = sysMenuMapper.selectList(queryWrapper3);
               for (SysMenu sM:sysMenus){
                   //把子菜单的每一条拷贝到VO里
                   MenuVO myMenu2 = new MenuVO();
                   BeanUtils.copyProperties(sM,myMenu2);
                   menuVOS.add(myMenu2);
               }

                item.setChildren(menuVOS);
            }
            return menus;
        }

        /**
         * 根据二级菜单获取三级菜单
         *
         * @param menus 拥有二级菜单的一级菜单
         * @return
         */
//        public List<MenuVO> handleChildMenus(List<MenuVO> menus) {
//            for (MenuVO item : menus) {
//                //再次遍历二级菜单获取到三级菜单
//                for (int i = 0; i < item.getChildren().size(); i++) {
//                    List<MenuVO> children = getMenuByParentId(item.getChildren().get(i).getId());
//                    item.getChildren().get(i).setChildren(children);
//                }
//            }
////        //删除所有父节点不为0的菜单
////        menus.removeIf(item -> item.getParentid() != 0);
//            return menus;
//        }




}


